{% set master = salt["pillar.get"]("rabbitmq:master") %}
{% set curr_ips = salt["network.ip_addrs"]() %}

stop rabbitmq:
  cmd.run:
    - name: service rabbitmq-server stop
Setting rabbitmq cluster:  
  {% if master["ip"] not in curr_ips %}
  file.managed:
    - name:  /var/lib/rabbitmq/.erlang.cookie
    - source: salt://rabbitmq/files/dev_erlang_cookie.txt
    - user: rabbitmq
    - group: rabbitmq
    - mode: 400
  {% endif %}
  cmd.run:
    - name: |
        #start check whether need add ip/hostname to hosts
        {% if not salt["hosts.has_pair"](master["ip"], master["hostname"]) %} 
        echo {{ master["ip"] }} {{ master["hostname"] }} >> /etc/hosts      
        {% endif %}
        {% if not salt["hosts.has_pair"](master["ip"], master["hostname"].split(".")[0]) %} 
        echo {{ master["ip"] }} {{ master["hostname"].split(".")[0] }} >> /etc/hosts        
        {% endif %}
        {% for slave_ip, slave_hostname in salt["pillar.get"]("rabbitmq:slave", {}).items() %}
        {% if not salt["hosts.has_pair"](slave_ip, slave_hostname) %}
        echo {{slave_ip}} {{slave_hostname}} >> /etc/hosts
        {% endif %}
        {% endfor %}
        #end check whether need add ip/hostname to hosts
        service rabbitmq-server start
        {% if master["ip"] in curr_ips %}
        cp -r /var/lib/rabbitmq/.erlang.cookie /srv/salt/rabbitmq/files/dev_erlang_cookie.txt
        {% endif %}
        {% if master["ip"] not in curr_ips %}
        rabbitmqctl stop_app
        #rabbitmqctl join_cluster nodename
        rabbitmqctl join_cluster rabbit@{{master["hostname"].split(".")[0]}}
        rabbitmqctl start_app
        {% endif %}
